// by atom
(function(){
	var version = "1.1";

	var doc = document,
		html = doc.getElementsByTagName("html")[0];

	var log = function(){
		if(console != "undefinded") console.log(arguments[0]);
	};
	var $ = function(){
		return doc.getElementById(arguments[0]);
	};
	var css = {
		add : function(target, name){
			target.className = (target.className+" "+name).split(" ").filter(function(s,i,a){return i == a.lastIndexOf(s);}).filter(function(e){return e}).join(" ");
		}, del : function(target, name){
			target.className = target.className.replace(name, "").split(" ").filter(function(e){return e}).join(" ");
		}, toggle : function(target, name){
			if(target.className.indexOf(name)<0){
				this.add(target, name);
			} else {
				this.del(target, name);
			}
		}
	};

	var path = {
		initialize : function(){
			if($("path")){
				css.toggle(doc.getElementsByTagName("html")[0], "path_inited_hidden");
				css.toggle($("path"), "hidden");
				return;
			}
			this.design.initialize();
			this.dev.initialize();
		}, play : function(){
			chrome.extension.sendRequest({cmd:"load"}, function(response){
				path.initialize();
				// background.html 에 값 호출
				chrome.extension.sendRequest({cmd:"save", data: {
					turn : (response && response.turn == "on") ? "off" : "on"
				}});
			});
		}, shortcut : {
			initialize : function(){
				chrome.extension.sendRequest({cmd:"key"}, function(response){
					window.addEventListener('keyup', function(e){
						if(e.which == response){
							path.play();
						}
					}, false);
				});
			}
		}, dev : {
			initialize : function(){
				//동틀
				//배포서버
				if(location.host.indexOf("html.") >= 0){
					this.ajax("/"+location.pathname.split("/")[1], function(){
						path.dev.cooking(arguments[0]);
					});
				} else {
				//로컬서버
					this.ajax("/", function(){
						path.dev.ajax(arguments[0].data.match(/href="(.[^]*)"/)[1], function(){
							path.dev.cooking(arguments[0]);
						});
					});
				}
				//log("dev initialize");
			}, cooking : function(){
				var data = arguments[0].data.match(/fileTree.?=.?[^;]+/gi)[0],
					result = data.substring(0, data.lastIndexOf("}")+1).replace(/\t|\n/gi,"").replace(/\t|\n/,"");

				eval(result);
				path.markup({
					json : fileTree,
					url : arguments[0].url || ""
				});
			}, event : {
				click : function(event){
					if(event.stopPropagation) event.stopPropagation();
					if(event && event.preventDefault){
						event.preventDefault();
					}
					if(event) event.returnValue = false;

					/*
					 * 처음 : 현재위치 기준 폴더 요소
					 * 폴더 : 클릭한 위치 기준 폴더 요소
					 * id : 현재위치 파일 || 폴더 요소
					*/

					var id = (this.pathname || location.pathname).split("/").filter(function(e){return e}).join("_"),
						target = $(id),
						child = this.parentNode ? this.parentNode.getElementsByTagName("ul")[0] || false : false;

					//부모 모두 활성화
					while(target){
						target = target.parentNode.id != "path" ? target.parentNode : false;
						if(target.tagName == "UL"){
							css.add(target, "open");
						}
						if(target.tagName == "LI"){
							if(target.getElementsByTagName("a")[0].className.indexOf("folder")>=0){
								if(this == target.getElementsByTagName("a")[0]){
									css.toggle(this, "folder_expend");
								} else {
									css.add(target.getElementsByTagName("a")[0], "folder_expend");
								}
							}
						}
					}

					//현재 위치 자식 폴더목록 활성화
					if(child) css.toggle(child, "open");

					if(event == "inited"){
						var target = $(id);

						css.add(target, "target");

						while(target){
							target = target.parentNode;

							if(target.tagName  == "LI"){
								var folder = target.getElementsByTagName("a")[0];

								if(folder && folder.className.indexOf("folder") >= 0){
									//현재 위치로 스크롤
									//location.href = "#"+folder.id;
									$("path").scrollTop = target.offsetTop-($("titPath").offsetHeight+10);
									return;
								}
							}
						}
					}

				}, mouseover : function(event){
					if(event.stopPropagation) event.stopPropagation();
					if(event && event.preventDefault){
						event.preventDefault();
					}
					// 이미지 mouseover 시 썸네일
					if(this.href.match(/\.gif|\.jpg|\.png/)){

						var viewer = $("Path_viewer") || doc.createElement("div"),
							target = this,
							image = new Image();

						if(!$("Path_viewer")) {
							doc.getElementsByTagName("body")[0].appendChild(viewer);
						} else {
							viewer.style.width = doc.body.offsetWidth+"px";
							viewer.style.display = "block";
						}

						viewer.id = "Path_viewer";
						viewer.innerHTML = '<a href="#none" id="btnClose" class="link_close">클릭시 창이 닫힙니다.</a><div id="Path_imageInfo"></div><div id="Path_imageStage"></div>';

						$("Path_imageInfo").innerHTML = '<strong class="txt_filename">'+target.href.split("/").reverse()[0]+'</strong><dl class="list_info"><dt>Dimensions</dt><dd id="Path_imageDimensions"></dd><dt>URL</dt><dd><a href="'+target.href+'" class="link">'+target.href+'</a></dd></dl>';
						$("btnClose").addEventListener("click", function(event){
							$("Path_viewer").style.display = "none";
						});

						image.onload = function(){
							$("Path_imageDimensions").innerHTML = $("Path_image").width+" x "+$("Path_image").height;

						};

						image.id = "Path_image";
						image.src = target.href;
						$("Path_imageStage").appendChild(image);

					}
				}
			}, ajax : function(url, exec){
				var http = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
				http.open("GET", url, false);
				http.onreadystatechange = function(){
					if(http.readyState == 4){
						exec({
							url : url,
							data : http.responseText
						});
					}
				};
				http.send();
				//log("ajax");
			}
		}, markup : function(param){
			var div = doc.createElement("div"),
				ul = doc.createElement("ul"),
				bar = doc.createElement("span");

			for(value in param.json){
				if(value.match(/^\.svn/) == null){// 설정폴더 데이터 제외
					var li = doc.createElement("li"),
						link = doc.createElement("a"),
						qr = doc.createElement("span"),
						path = (param.url || param.path || "")+"/"+value,
						depth = param.depth || 1;

					link.id = path.split("/").filter(function(e){return e}).join("_");
					link.href = path;
					link.innerHTML = '<span class="ico"></span>'+value;
					link.className = (typeof param.json[value] == "object") ? "folder" : "file "+((value.indexOf(".") > 0) ? "file_"+value.split(".")[1] : "file_unknown"); //현재데이터 형식 class 정의
					link.style.textIndent = (depth*1.35)+"em";

					//QR
					qr.className = "qr";
					qr.innerText = "QR코드";
					qr.title = "클릭하시면 QR코드 레이어가 나타납니다.";
					qr.addEventListener("click", function(event){
						if(event.stopPropagation) event.stopPropagation();
						if(event && event.preventDefault){
							event.preventDefault();
						}
						if(this.getElementsByTagName("span").length < 1){
							var thumb = doc.createElement("span");
							thumb.className = "thumb";
							thumb.innerHTML = '<img src="http://chart.apis.google.com/chart?cht=qr&chs=260x260&choe=UTF-8&chld=H|0&chl='+this.parentNode.href+'" alt="QR" class="img" />';
							this.appendChild(thumb);
						}
					});
					qr.addEventListener("mouseout", function(event){
						if(event.stopPropagation) event.stopPropagation();
						if(event && event.preventDefault){
							event.preventDefault();
						}
						if(this.getElementsByTagName("span")[0]){
							this.removeChild(this.getElementsByTagName("span")[0]);
						}
					});
					link.appendChild(qr);

					link.addEventListener("mouseover", this.dev.event.mouseover);

					if(typeof param.json[value] == "object"){
						link.addEventListener("click", this.dev.event.click);
					}

					li.appendChild(link);

					if(param){// 하위 path 존재시 depth class 정의
						ul.className = "depth_"+depth;
						depth++;
					}

					if(typeof param.json[value] == "object"){//하위 path 존재시 하위 폴더 markup
						this.markup({
							json : param.json[value],
							target : li,
							path : path,
							depth : depth
						});
					}

					if(link.className == "folder" && ul.getElementsByTagName("li").length){
						ul.insertBefore(li, ul.getElementsByTagName("li")[0]);
					} else {
						ul.appendChild(li);
					}
				}
			}

			if(param.target){
				param.target.appendChild(ul);
			} else {
				//최초
				html.className += (html.className ? " " : "")+"path_inited";

				css.add(ul, "list_path");
				div.setAttribute("id", "path");
				div.innerHTML = '<strong id="titPath" class="tit_path">Path '+version+'</strong>';
				div.appendChild(ul);

				/*리사이즈바*/
				css.add(bar, "path_bar");
				bar.id = "pathBar";
				bar.clicked = false;

				window.addEventListener("mousemove", function(e){
					/*if($("pathBar").clicked == false && e.clientX < 0){
						$("pathBar").clicked = true;
					}
					if($("pathBar").clicked && e.clientX >0 ){
						$("pathBar").clicked = true;
					}*/
					if($("pathBar").clicked){
						if($("path").offsetLeft < e.clientX){
							/*doc.getElementsByTagName("html")[0].style.marginLeft = (e.clientX+2)+"px";*/
							$("titPath").style.width = (e.clientX-20)+"px";
							$("path").style.width = (e.clientX-2)+"px";
							$("pathBar").style.left = (e.clientX-1)+"px";
							$("pathBar").style.left = (e.clientX-1)+"px";

							if($("Path_viewer")){
								$("Path_viewer").style.left = (e.clientX+4)+"px";
								$("Path_viewer").style.width = doc.body.offsetWidth+"px";
							}

							var data = {
								titPath : (e.clientX-20)+"px",
								path : (e.clientX-4)+"px",
								pathBar : e.clientX+"px",
								Path_viewer_left : (e.clientX+4)+"px",
								Path_viewer_width : (doc.body.clientWidth-$("path").offsetWidth)+"px"

							}
						}
					}
				});
				bar.addEventListener("mousedown", function(){
					doc.onselectstart = function(){return false;};
					this.clicked = true;
				});
				window.addEventListener("mouseup", function(){
					doc.onselectstart = function(){return true;};
					bar.clicked = false;
				});

				div.appendChild(bar);

				document.getElementsByTagName("body")[0].appendChild(div);

				this.dev.event.click("inited");
			}
			//log("markup");
		}, design : {
			initialize : function(){
				/*var link = document.createElement("link");
				link.setAttribute("rel", "stylesheet");
				link.setAttribute("type", "text/css");
				link.setAttribute("href", "path.css?"+(new Date().getTime()));
				(document.getElementsByTagName("head")[0] || document.getElementsByTagName("body")[0]).appendChild(link);*/
				//log("design initialize");
			}
		}
	};
	//window.addEventListener("DOMContentLoaded", function(){
		path.shortcut.initialize();

		// background.html 에 값 호출
		chrome.extension.sendRequest({cmd:"load"}, function(response){
			if(response && response.turn == "on"){
				path.initialize();
			}
		});
		// background.html 에서 호출시 대응
		chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
			path.play();
		});
	//}, false);
})();